import Vue from 'vue';
import { isQualityRuleStartTimeField, isQualityTimeField, getFieldName } from '@service/FieldService.ts';
import { isNumber } from '@src/util/type';
import { cloneDeep } from 'lodash'
import { getProductQualityStatusText } from '@src/util/qualityInfoConfig'
import { ProductFieldNameMappingEnum ,FieldTypeMappingEnum} from '@model/enum/FieldMappingEnum'
import { fmt_address } from '@src/filter/fmt';
import { isObjectString } from '@src/component/form/components/FormJsControl/model/index';
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'
import { t } from '@src/locales'
import { openViewRichText } from '@src/common/entry.js'

const { internationalGray } = useFormMultiLanguage()

import { formatDate, isPlainObject, isUndef, isEmpty, isString, isArray, useFormTimezone } from 'pub-bbx-utils';
const { isSystemTime, isCustomTimeField, isSystemTimeField, genColumnFormatMap } = useFormTimezone();

/**
 * 格式化表单设计器特殊字段显示
 *
 * @param {string} value 格式前的值
 * @param {string} formType 控件类型
 * @param {string} fieldName 字段名
 * @param {string} field 字段对象，目前是涉及多级菜单的必传
 */
export const formatFormField = function (column, row, attributeName = 'attribute') {
  if (!column || !row) {
    return '';
  }
  try {
    const attribute = row[attributeName];
    let { field, fieldName } = column;
    // 表单内的有限使用field，没有的话使用fieldName
    let value = row[field || fieldName] ?? attribute?.[field || fieldName];

    return formatFormFieldItem(column, value);
  } catch (error) {
    console.warn('formatFormField error:', error, column, row, attributeName);
    return '';
  }
};

/**
 * 格式化表单设计器特殊字段显示 -- 明确value
 * @param {*} field 
 * @param {*} value 
 * @returns 
 */
export function formatFormFieldItem(field = {}, value) {
  let { formType = '', fieldName = '', setting } = field;
  
  if (setting?.originalFormType) {
    // FormMaterialsBillBuild.vue 有
    formType = setting?.originalFormType;
  }
  // 处理产品关联产品字段质保开始日期质保结束日期
  if (formType === FieldTypeMappingEnum.RelatedProduct) {
    if([ProductFieldNameMappingEnum.QualityStartTime, ProductFieldNameMappingEnum.QualityEndTime].includes(setting?.fieldName)){
      const formatData = (value || [])?.map(item => formatDate(item, setting?.formType));
      return fmt_form_default(formatData);
    }
  }
  
  
  // 空值直接返回
  if(isUndef(value)) return ''
  
  if (fieldName == 'tags') {
    return fmt_tags(value);
  }
  
  if (fieldName == ProductFieldNameMappingEnum.QualityInfoStatus) {
    // 兼容
    const valueMap = {
      IN: 'In',
      OUT: 'Out',
    }
    return getProductQualityStatusText(valueMap[value] || value)
  }
  
  if ((isSystemTime(fieldName) || isSystemTimeField(field) || isCustomTimeField(field))) {
    // 后端所有时间都是时间戳，前端只需要格式化
    // 如果不是时间戳的，这里会认为已经根据时区格式化过了，就不处理了
    const format = genColumnFormatMap(formType, setting?.dateType);
    return formatDate(value, format);
  }
  
  const formatMapByType = {
    // 多级菜单
    cascader: () => fmt_form_cascader(value, !!setting?.isMulti, setting?.displayMode),
    // 下拉菜单
    select: () => fmt_form_select(value),
    // 人员
    user: () => fmt_form_user(value),
    // 关联工单
    related_task: () => fmt_form_related_task(value),
    // 地址
    address: () => fmt_form_address(value),
    // 位置
    location: () => fmt_form_location(value),
    // 物流
    logistics: () => fmt_form_logistics(value, fieldName),
    // 货币
    currency: () => fmt_currency(value),

    jsCodeBlock: ()=>  fmt_js_code_block(value),

    tag: () => fmt_tag(value),
  };
  return formatMapByType[formType]?.() ?? fmt_form_default(value);
}

export function fmt_form_quality_rule(column, form) {
  let fieldName = getFieldName(column);
  let formatValue = '';

  if (isQualityRuleStartTimeField(column)) {
    formatValue = fmt_form_quality_start_time(form);
  } else if (isQualityTimeField(column)) {
    formatValue = fmt_form_quality_time(form);
  } else {
    formatValue = form[fieldName] || '';
  }

  return formatValue;
}

/** 多级菜单 */
export function fmt_form_cascader(val, isMulti = false, displayMode) {
  let value = cloneDeep(val)
  if (isEmpty(value)) return '';
  if (isString(value)) {
    return value;
  }
  if (isArray(value)) {
    try {
      // 只显示勾选节点
      if (isMulti && displayMode != 2) {
        value = value.map(item => item.split('/').pop());
      }
      if (!isMulti && displayMode == 1) {
        return value.pop();
      }
      return value.join(isMulti ? ',' : '/');
    } catch (error) {
      console.error(error) 
    }
  }
  return '';
}

/** 下拉 */
export function fmt_form_select(value) {
  if (isEmpty(value)) return '';
  return isArray(value)
    ? value.join(',')
    : isString(value)
      ? value
      : ''
}

/** 人员（支持多选） */
export function fmt_form_user(value) {
  // 多选
  if (Array.isArray(value)) {
    return value.map(i => i.displayName || i.name).join(',');
  }

  let user = value || {};

  return user.displayName || user.name || '';
}

/** 关联工单 */
export function fmt_form_related_task(value) {
  return Array.isArray(value) ? value.map(item => item.taskNo).join(',') : '';
}

/** 字符串数组 */
export function fmt_form_array(value) {
  return value && value.join(', ');
}
/** 地址 */
export function fmt_form_address(value) {
  // const { province, city, dist, address } = value;		
  // return value ? [province, city, dist, address].filter(d => !!d).join('-') : '';

  // 代码迁移到了pub-bbx-utils
  return fmt_address(value,'-');
}
/** 位置 */
export function fmt_form_location(value) {
  if(!isPlainObject(value)) return ''
  return value?.address || '';
}

/* 日期时间 */
export const fmt_form_date = function (value, format = 'date') {
  return formatDate(value, format);
};

/** 默认格式化 */
export function fmt_form_default(value) {
  if (Array.isArray(value)) {
    return fmt_form_array(value);
  }

  return value;
}

/** 质保开始时间 */
export function fmt_form_quality_start_time(form) {
  return form?.qualityStartDate || '';
}

/** 质保时长 */
export function fmt_form_quality_time(form) {
  const qualityDuration = isNumber(form?.qualityDuration) ? form?.qualityDuration : form?.qualityDuration || '';
  return qualityDuration + (form?.qualityUnit || '');
}

/**
 * 物流格式化
 * @param {*} value
 * @returns
 */
export function fmt_form_logistics(value, fieldName) {
  if (!value || !value.length) return '';

  const [{ company = { name: '' }, no = '' }] = value;

  return fieldName.indexOf('company') > -1 ? (company?.name ?? '') : (no ?? '');
}

export function fmt_tags(value = []) {
  return value?.map(item => item?.name || item?.tagName).join('，');
}

export function fmt_salePrice_currency(value) {
  let price = value.salePrice || 0
  let salePriceCurrency = value?.salePriceCurrency || 'CNY'
  if(internationalGray) {
      return `${price} ${salePriceCurrency}`
  }
  return price
}
export function fmt_total_currency(value) {
  let price = value.total || 0
  let salePriceCurrency = value?.salePriceCurrency || 'CNY'
  if(internationalGray) {
      return `${price} ${salePriceCurrency}`
  }
  return price
}
// 列表的国际货币字段展示
export function fmt_currency(value = {}) {
  if(!value.number && value.number !== 0) return '';

  return `${value.number} ${value?.currency || ''}`;
}


export function fmt_js_code_block(value = '') {
  return isObjectString(value) ? Object.values(JSON.parse(value)).join(',') : ''
}

export function fmt_richtext(value = '') {
  if(isEmpty(value)) return '';

  return (
      <div class='view-detail-btn' onClick={() => openViewRichText(value) }>{t('common.base.view')}</div>
  )
}

export function fmt_tag(value) {
  if (Array.isArray(value)) {
    return value.map(i => i.displayName || i.name).join(',');
  }
  return value?.displayName || value?.name || '';
}

Vue.prototype.$formatFormField = formatFormField;

export default {
  fmt_form_date,
  fmt_form_cascader,
  fmt_form_select,
  fmt_form_user,
  fmt_form_related_task,
  fmt_form_address,
  fmt_form_location,
  fmt_form_default,
  fmt_currency,
  fmt_salePrice_currency,
  fmt_total_currency,
  fmt_js_code_block
};
